// 收货地址相关API调用工具
const app = getApp();

// API基础配置
const API_BASE = 'http://localhost:8080/api/wx/address';

/**
 * 统一请求方法
 */
function request(url, method = 'GET', data = {}) {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token') || '';
    
    wx.request({
      url: url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': token
      },
      success: (res) => {
        console.log('API请求成功:', url, res.data);
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: (error) => {
        console.error('API请求失败:', url, error);
        reject(error);
      }
    });
  });
}

/**
 * 获取用户所有收货地址
 */
export function getUserAddresses() {
  return request(`${API_BASE}/list`);
}

/**
 * 根据ID获取地址详情
 */
export function getAddressById(id) {
  return request(`${API_BASE}/${id}`);
}

/**
 * 新增收货地址
 */
export function createAddress(addressData) {
  return request(`${API_BASE}/create`, 'POST', addressData);
}

/**
 * 更新收货地址
 */
export function updateAddress(id, addressData) {
  return request(`${API_BASE}/${id}`, 'PUT', addressData);
}

/**
 * 删除收货地址
 */
export function deleteAddress(id) {
  return request(`${API_BASE}/${id}`, 'DELETE');
}

/**
 * 设置默认地址
 */
export function setDefaultAddress(id) {
  return request(`${API_BASE}/${id}/default`, 'PUT');
}

/**
 * 获取默认地址
 */
export function getDefaultAddress() {
  return request(`${API_BASE}/default`);
}

/**
 * 显示成功提示
 */
export function showSuccess(message) {
  wx.showToast({
    title: message,
    icon: 'success',
    duration: 2000
  });
}

/**
 * 显示错误提示
 */
export function showError(message) {
  wx.showToast({
    title: message,
    icon: 'error',
    duration: 2000
  });
}

/**
 * 显示加载中
 */
export function showLoading(title = '加载中...') {
  wx.showLoading({
    title: title,
    mask: true
  });
}

/**
 * 隐藏加载
 */
export function hideLoading() {
  wx.hideLoading();
}
